package com.lihaozhe.orderservice.controller;

import com.lihaozhe.orderservice.dto.OrderDTO;
import com.lihaozhe.orderservice.dto.OrderItemDTO;
import com.lihaozhe.orderservice.service.ServiceDiscoveryService;
import com.lihaozhe.productservice.dto.ProductDTO;
import com.lihaozhe.userservice.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单服务控制器
 * 演示如何通过Eureka发现和调用其他服务
 *
 * @author 李昊哲
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/orders")
public class OrderController {

  private final ServiceDiscoveryService serviceDiscoveryService;
  private final List<OrderDTO> orders = new ArrayList<>();
  private Long orderIdCounter = 1L;
  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  /**
   * 构造函数，注入服务发现工具类
   */
  public OrderController(ServiceDiscoveryService serviceDiscoveryService) {
    this.serviceDiscoveryService = serviceDiscoveryService;
  }

  /**
   * 创建订单
   * POST /api/orders
   * 演示调用用户服务和商品服务
   */
  @PostMapping
  public Map<String, Object> createOrder(@RequestBody Map<String, Object> orderRequest) {
    Long userId = Long.valueOf(orderRequest.get("userId").toString());
    Long productId = Long.valueOf(orderRequest.get("productId").toString());
    Integer quantity = Integer.valueOf(orderRequest.get("quantity").toString());

    logger.info("创建订单 - 用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity);

    try {
      // 1. 调用用户服务验证用户是否存在
      UserDTO user = serviceDiscoveryService.getUserById(userId);
      if (user == null) {
        return Map.of("success", false, "message", "用户不存在");
      }

      // 2. 调用商品服务获取商品信息
      ProductDTO product = serviceDiscoveryService.getProductById(productId);
      if (product == null) {
        return Map.of("success", false, "message", "商品不存在");
      }

      // 3. 检查库存
      if (product.getStock() < quantity) {
        return Map.of("success", false, "message", "库存不足");
      }

      // 4. 创建订单
      OrderItemDTO orderItem = new OrderItemDTO(productId, product.getName(), quantity, product.getPrice());
      List<OrderItemDTO> items = List.of(orderItem);
      Double totalAmount = product.getPrice() * quantity;

      OrderDTO order = new OrderDTO(orderIdCounter++, userId, items, totalAmount, "CREATED");
      orders.add(order);

      // 5. 调用商品服务更新库存
      boolean stockUpdated = serviceDiscoveryService.updateProductStock(productId, -quantity);
      if (!stockUpdated) {
        return Map.of("success", false, "message", "库存更新失败");
      }

      return Map.of(
          "success", true,
          "message", "订单创建成功",
          "orderId", order.getId(),
          "totalAmount", totalAmount,
          "user", user.getUsername(),
          "product", product.getName()
      );

    } catch (Exception e) {
      return Map.of("success", false, "message", "创建订单失败: " + e.getMessage());
    }
  }

  /**
   * 根据订单ID获取订单详情
   * GET /api/orders/{orderId}
   */
  @GetMapping("/{orderId}")
  public OrderDTO getOrder(@PathVariable("orderId") Long orderId) {
    return orders.stream()
        .filter(o -> o.getId().equals(orderId))
        .findFirst()
        .orElse(null);
  }

  /**
   * 获取用户的所有订单
   * GET /api/orders/user/{userId}
   */
  @GetMapping("/user/{userId}")
  public List<OrderDTO> getUserOrders(@PathVariable("userId") Long userId) {
    // 先验证用户是否存在
    UserDTO user = null;
    try {
      user = serviceDiscoveryService.getUserById(userId);
      if (user == null) {
        return List.of();
      } else {
        return orders.stream().filter(o -> o.getUserId().equals(userId)).toList();
      }
    } catch (Exception e) {
      System.err.println("验证用户失败: " + e.getMessage());
      return List.of();
    }
  }

  /**
   * 获取所有注册的服务
   * GET /api/orders/services
   */
  @GetMapping("/services")
  public List<String> getServices() {
    return serviceDiscoveryService.getServices();
  }

  /**
   * 健康检查端点
   * GET /api/orders/health
   */
  @GetMapping("/health")
  public Map<String, Object> health() {
    return Map.of(
        "status", "UP",
        "service", "order-service",
        "timestamp", System.currentTimeMillis(),
        "totalOrders", orders.size()
    );
  }

  /**
   * 服务信息端点
   * GET /api/orders/info
   */
  @GetMapping("/info")
  public Map<String, Object> info() {
    return Map.of(
        "name", "order-service",
        "description", "订单管理服务",
        "version", "1.0.0",
        "dependencies", List.of("user-service", "product-service")
    );
  }
}
